const app = getApp();
const Api = app.globalData.Api;
const util = app.globalData.util;
const wxApi = app.globalData.wxApi;

Page({
  data: {
    type: 2,
    messages: [],
    infoviewShow: false
  },
  onShow() {
    wx.hideNavigationBarLoading();
    this.init();
  },
  onLoad() {
    wxApi.setNavTitle('消息')
  },
  init() {
    this.refresh();
  },
  onTabMessage( e ) {
    let type = e.currentTarget.dataset.type;
    
    this.setData({
      type: type
    });
    this.refresh();
  },
  refresh() {
    let type = this.data.type;
    this.loadMessages(type, 1, messages => {
      console.log( messages );
      this.setData({
        messages: messages,
        infoviewShow: !messages.length
      })
    })
  },
  loadMessages(type, pageNo, callback) {
    let params = {
      type: type,
      pageNo: pageNo
    }
    Api.messages(params, res => {
      let messages = res.records;
      messages = this.messagesDateFormat( messages );
      console.log(messages);
      callback( messages );
    })
  },
  messagesDateFormat( messages ) {
    let newMessages = [];
    for ( let i = 0, len = messages.length; i < len; i ++ ) {
      let message = messages[ i ];
      message.dateTime = util.dateFormat('yyyy.MM.dd mm:ss', message.createTime);
      newMessages.push( message );
    }
    return newMessages;
  },
  gotoMessageDetail( e ) {
    let message = e.currentTarget.dataset.message;
    if (!message.read) {
      Api.messageRead( message.id, (res, code) => {
        console.log(code);
        console.log( res );
      } )
    }
    let params = {
      src: message.content
    }
    console.log(params);
    wxApi.navigateTo('../common/webview/webview', params)
  }
})